package jdk5.annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

import jdk5.meta.Ignore;
import jdk5.meta.Test;

public class TestTools {

	private int success;

	private int failure;

	private Class<?> testClass;
	private Object instance;

	public TestTools(Class<?> testClass) {
		this.testClass = testClass;
		try {
			this.instance = this.testClass.getConstructor().newInstance();
		} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
				| NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		// 1.判断
		if (this.testClass == null) {
			System.out.println("没有指定被测的对象...");
			return;
		}
		//
		Method[] methods = this.testClass.getMethods();
		// 2. 获取此类是否添加了@Test注解
		if (this.testClass.isAnnotationPresent(Test.class)) {
			// 则判断此类中的方法是否有加 ignore 注解
			Arrays.stream(methods).filter((m) -> !m.isAnnotationPresent(Ignore.class)).forEach((m) -> {
				// 调用
				try {
					m.invoke(this.instance);
					//
					this.success++;

				} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
					//
					this.failure++;
					System.out.printf("Test %s failed: %s%n", m.getName(), e.getCause());
				}
			});
			//
			System.out.printf("Passed: %d, failed %d%n", success, failure);

		} else {
			// 则判断方法是否有添加 Test 注解
			Arrays.stream(methods).filter((m) -> m.isAnnotationPresent(Test.class)).forEach((m) -> {
				// 调用
				try {
					m.invoke(this.instance);
					//
					this.success++;

				} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
					//
					this.failure++;
					System.out.printf("Test %s failed: %s%n", m.getName(), e.getCause());
				}
			});
			//
			System.out.printf("Passed: %d, failed %d%n", success, failure);
		}
	}
}
